package com.atcjx.MyUtils.File;

import com.atcjx.exception.UserException;
import com.atcjx.exception.exceptionEnum;
import com.atcjx.pojo.Article.Article;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;



import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;


/**
 * @author admin
 * @version 1.0.0
 * @ClassName FileUtils.java
 * @Description TODO
 * @createTime 2021年10月08日 19:56:00
 */
public class FileUtils {
    /**
     * 描述：获取一个文件名称的后缀格式
     * @Date 2021/10/8 19:56
     * @param fileName
     * @return
     */
    public static String fileSuffix(String fileName){
        if(!fileName.contains("."))
            return null;
        int lastIndexOf=fileName.lastIndexOf('.');
        return fileName.substring(lastIndexOf);
    }
    /**
     * inputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception{
        //System.getProperty("java.io.tmpdir")临时目录+File.separator目录中间的间隔符+文件名
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
//        if (file.exists()) {
//            return file;
//        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

    /**
     * file转multipartFile
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(file.getName(), "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

    /**
     * url转MultipartFile
     */
    public static MultipartFile urlToMultipartFile(String url) throws Exception {
        File file = null;
        MultipartFile multipartFile = null;
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
            httpUrl.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            httpUrl.connect();
            file = inputStreamToFile(httpUrl.getInputStream(),"template.png");
            multipartFile = fileToMultipartFile(file);
            httpUrl.disconnect();
        } catch (Exception e) {
            throw new UserException(exceptionEnum.ERRORURL.getMsg(),exceptionEnum.ERRORURL.getCode());
        }
        return multipartFile;
    }
    /**
     * @Author Cjx_71023
     * @Description //TODO 传入参数在本地打开该文章
     * @Date 22:49 2021/12/6
     * @Param [article, baseURL, theme]
     * @return void
     **/
    public static void openFile(Article article,String baseURL) throws UserException {
        String url = baseURL + File.separator + article.getTheme() + File.separator + article.getCategory() + File.separator + article.getTitle() + ".md";
        File file=null;
        try {
            file = new File(url);
            Desktop.getDesktop().open(file);
        } catch (Exception e) {
            System.out.println("异常！！！");
            throw new UserException(exceptionEnum.NOFILESEARCH.getMsg(), exceptionEnum.NOFILESEARCH.getCode());
        }
    }
    /**
     * @Author Cjx_71023
     * @Description //TODO 将文章保存到本地
     * @Date 15:29 2021/12/7
     * @Param
     * @return
     **/
    public static void updateArticleLocal(Article article,String baseURL) throws UserException {

        String content = article.getContent();
        String url = baseURL + File.separator + article.getTheme() + File.separator + article.getCategory() + File.separator + article.getTitle() + ".md";
        File file = new File(url);
        FileWriter outputStream=null;
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            outputStream =  new FileWriter(file);
            outputStream.write(content);
        } catch (IOException e) {
            throw new UserException(exceptionEnum.WRITELOCALFILEERROR.getMsg().concat(file.getPath()), exceptionEnum.WRITELOCALFILEERROR.getCode());
        }
        finally {
            try {
                if(outputStream!=null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
